﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading.Tasks;

namespace xycn.framework.Common
{
    /// <summary>
    /// 多平台支持代码
    /// </summary>
    public static class MultiOSSupportExtension
    {
        /// <summary>
        /// 获取程序运行目录
        /// </summary>
        /// <returns></returns>
        public static string GetProgramRuntimeDir()
        {
            string path = Assembly.GetExecutingAssembly().Location;
            //将该路径传递给 System.IO.Path.GetDirectoryName(path)，获得执行程序集所在的目录
            return TranslateDirectory(Path.GetDirectoryName(path) + "\\");
        }

        /// <summary>
        /// 根据绝对路径和相对路径，计算给定相对路径对应的绝对路径。
        /// 如果输入的相对路径参数为绝对路径，则直接返回输入路径
        /// </summary>
        /// <param name="base_absolutedir"></param>
        /// <param name="relative_dir"></param>
        /// <returns></returns>
        public static string CalculateAbsoluteDir(string base_absolutedir, string relative_dir)
        {
            Uri uri_p3 = new Uri(base_absolutedir, UriKind.Absolute);
            Uri uri_P4 = new Uri(relative_dir, UriKind.Relative);
            Uri uri_result = new Uri(uri_p3, uri_P4);
            string ret = uri_result.LocalPath;
            return TranslateDirectory(ret);
        }

        /// <summary>
        /// 根据当前运行平台自动转化路径
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static string TranslateDirectory(string path)
        {
            string pathTemp = Path.Combine(path);
            if (IsLinuxRunTime())
            {
                pathTemp =  pathTemp.Replace("\\", "/");
            }

            if (IsWindowRunTime())
            {
                pathTemp = pathTemp.Replace("/", "\\");
            }

            return pathTemp;
        }

        /// <summary>
        /// 判断运行时操作系统是否windows
        /// </summary>
        /// <returns></returns>
        public static bool IsWindowRunTime()
        {
            return System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
        }

        /// <summary>
        /// 判断运行时操作系统是否linux
        /// </summary>
        /// <returns></returns>
        public static bool IsLinuxRunTime()
        {
            return System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(OSPlatform.Linux);
        }
    }
}
